package algorithm.linkedlist;

import algorithm.model.ListNode;

/**
 * leetcoode : https://leetcode.com/problems/merge-two-sorted-lists/description/
 * Difficulty : Easy
 *
 * 合并两个有序的链表，思路不讲了，太简单
 *
 * 看到一个递归解法，很巧妙，而且时间很短，只需要 1ms
 * https://leetcode.com/problems/merge-two-sorted-lists/discuss/9715/Java-1-ms-4-lines-codes-using-recursion
 *
 * @Author Antony
 * @Since 2018/7/11 22:14
 */
public class MergeTwoSortedLists {

    public static void main(String[] args) {
        ListNode list_1 = ListNode.initDate(new int[]{1,2,4,6});
        ListNode list_2 = ListNode.initDate(new int[]{1,3,4,7});
        System.out.println(mergeTwoLists(list_1, list_2).nodeString());

    }

    /**
     * (beats 100.0% - 8ms)
     */
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode first = dummy;
        ListNode tmp;
        while(l1!=null && l2!=null){
            if(l1.val < l2.val){
                tmp = l1;
                l1  = l1.next;
            }else{
                tmp = l2;
                l2 = l2.next;
            }
            tmp.next = null;
            dummy = dummy.next = tmp;
        }
        if(l1 != null) dummy.next = l1;
        if(l2 != null) dummy.next = l2;

        return first.next;
    }


    // (1ms 递归解法)
    // https://leetcode.com/problems/merge-two-sorted-lists/discuss/9715/Java-1-ms-4-lines-codes-using-recursion
    public static ListNode mergeTwoLists_recursion(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        if(l1.val < l2.val){
            l1.next = mergeTwoLists_recursion(l1.next, l2);
            return l1;
        } else{
            l2.next = mergeTwoLists_recursion(l1, l2.next);
            return l2;
        }
    }
}
